package com.by.gateway.service;

import com.by.rpc.dto.ServiceInstance;
import com.by.rpc.util.KeyUtils;
import com.by.rpc.util.ServiceParameter;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author lby
 * @description
 * @date 2025/7/27 16:45
 */
@Builder
@Data
@NoArgsConstructor
@AllArgsConstructor
public class EndpointInfo {
    private String serviceName;
    private String routePath;
    private String httpMethod;
    private String rpcMethodName;
    private String version;
    private String group;
    private ServiceInstance serviceInstance;
    Map<String,String> pathVariables;
    private List<ServiceParameter> serviceParameters = new ArrayList<>();

    public static EndpointInfo parse(String endpointKey, String endpointVal) {
        String[] endpointParts = endpointKey.split(KeyUtils.RPC_SPLIT);
        String serviceName = endpointParts[0];
        String version = endpointParts[1];
        String group = endpointParts[2];
        String endpointPath = endpointParts[3];
        String endpointMethod = endpointParts[4];

        EndpointInfo endpointInfo = EndpointInfo.builder()
                .httpMethod(endpointMethod)
                .routePath(endpointPath)
                .serviceName(serviceName)
                .version(version)
                .group(group)
                .build();
        String[] parts = endpointVal.split("\\|", 2);
        if (parts.length < 1) {
            throw new IllegalArgumentException("Invalid method signature: " + endpointVal);
        }

        endpointInfo.setRpcMethodName(parts[0]);
        List<ServiceParameter> serviceParameters = new ArrayList<>();
        if (parts.length > 1 && !parts[1].isEmpty()) {
            String[] paramStrings = parts[1].split(",");
            for (int i = 0; i < paramStrings.length; i++) {
                String paramString = paramStrings[i].trim();
                if (paramString.isEmpty()) continue;

                String[] typeAndName = paramString.split(":", 5);
                if (typeAndName.length != 5) {
                    throw new IllegalArgumentException("Invalid parameter format: " + paramString);
                }
                int paramOrder = Integer.parseInt(typeAndName[0].trim());
                String paramName = typeAndName[1].trim();

                String paramType = typeAndName[2].trim();
                String alias = typeAndName[3].trim();
                String position = typeAndName[4].trim();
                serviceParameters.add(new ServiceParameter(paramOrder, paramName, paramType, position, null, alias));
            }
        }
        endpointInfo.setServiceParameters(serviceParameters);
        return endpointInfo;
    }
}

